const fs = require("fs");
const execa = require("execa");
const inquirer = require("inquirer");
const menu = require("../utils/menu");
inquirer.registerPrompt("search-list", require("inquirer-search-list"));
const has = (res, key) => Object.prototype.hasOwnProperty.call(res, key);
module.exports = (options) => {
  if (has(options, "select")) {
    const select = options.select;
    if (select && typeof select === "string") {
      let dir = "";
      let desc = "";
      menu.forEach((val) => {
        if (val.name === select) {
          dir = val.value.basePath + val.value.path;
          desc = val.value.desc;
        }
      });
      if (dir) {
        console.log(`正在打开${desc}`);
        execa(`code -n ${dir}`);
      } else {
        console.log(`还未配置${select}对应项目目录`);
      }
    } else {
      inquirer
        .prompt([
          {
            name: "project",
            type: "search-list",
            message: "请选择启动的项目",
            choices: menu,
          },
        ])
        .then((res) => {
          let dir = res.project.basePath + res.project.path;
          console.log(`正在打开${res.project.desc}`);
          execa(`code -n ${dir}`);
        })
        .catch((err) => {
          console.log(err);
        });
    }
    return;
  }
  if (options.file) {
    if (/^hosts?$/.test(options.file)) {
      console.log(`正在打开host配置文件`);
      execa("code C:/Windows/System32/drivers/etc/hosts");
    } else if (/^nginx$/.test(options.file)) {
      console.log(`正在打开本地nginx配置文件`);
      execa("code D:/nginx-1.20.2/conf/nginx.conf");
    } else if (/^redis$/.test(options.file)) {
      console.log(`正在打开本地redis配置文件`);
      execa("code D:/redis/redis.windows.conf");
    } else {
      fs.stat(options.file, (err, stats) => {
        if (err) {
          // 操作异常
          console.log("无法识别文件");
        } else {
          console.log(`正在打开${options.file}`);
          if (stats.isFile()) {
            let url = options.file.replace(/\\/g, "/");
            // 文件
            execa(`code ${url}`);
          } else if (stats.isDirectory()) {
            let url = options.file.replace(/\\/g, "/");
            // 目录
            execa(`code -n ${url}`);
          }
        }
      });
    }
    return;
  }
};
